# -*- coding: utf-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.header import Header
import requests
import schedule
import time
import datetime
import ssl

import os
import re
 


requests.packages.urllib3.disable_warnings()
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE

#黄金网站
url = "https://www.sge.com.cn/hqsj"

def url_open(url):
    try:
        page_headers={
         'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0',
         }
        res=requests.get(url,headers=page_headers,verify=False)
        status=res.status_code
        data=res.text
        return data
    except:
        pass
    
def get_today():
    h=datetime.datetime.now()
    today=h.strftime("%Y-%m-%d")    
    return today

def get_gold():
    try:
        data=url_open(url)
        return data
    except:
        return "无法获取到黄金价格信息"





def delete_files(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if re.match('filename.*\.ttt$', file): # 这里的正则表达式为删除所有后缀名为".txt"的文件
                path = os.path.join(root, file)
                os.remove(path)




def set_content():
    subject=get_gold()
    today_data=get_today()
    content="<div class='todayTitle'>今天是"+today_data+"</div>"+subject
    print(today_data)
    # 调用函数并传入目标文件夹路径
    delete_files('/usr/local/nginx/html')

    with open('/usr/local/nginx/html/filename'+today_data+'.ttt','w+') as file:
        file.write(content)
        file.close()


 


def mail_qq(subject,content):
    mail_host="smtp.qq.com"#设置服务器
    mail_user="1xxxx@qq.com"#用户名
    mail_pass="fobbaybdiubfgjhd"#密码
    sender="1xx@qq.com"
    receivers=['1xxxxxxx@qq.com']#接收邮件
    try:
        message=MIMEText(content,'plain','utf-8')
        message['From']=Header("小平",'utf-8')#发件人昵称
        message['To']=Header("小平",'utf-8')#收件人昵称
        
        message['Subject']=Header(subject,'utf-8')
        
        server=smtplib.SMTP_SSL(mail_host,465)
        server.login(mail_user,mail_pass)
        server.sendmail(sender,receivers,message.as_string())
        
        server.quit()#关闭链接
        print("邮件发送成功")
    except Exception as e:
        print(e)
        print("邮件发送失败")
        

if __name__=="__main__":
    set_content()
    schedule.every(5).minutes.do(set_content)

while True:
    schedule.run_pending()
    time.sleep(1)